import { createRouter, createWebHistory } from 'vue-router'

import LayoutContainer from '@/views/layout/LayoutContainer.vue'
import CategoryManagement from '@/views/DishManagement/CategoryManagement.vue'
import CostManagement from '@/views/DishManagement/CostManagement.vue'
import DishList from '@/views/DishManagement/DishList.vue'
import FlavorManagement from '@/views/DishManagement/FlavorManagement.vue'

import HistoricalOrders from '@/views/OrderManagement/HistoricalOrders.vue'
import OrderList from '@/views/OrderManagement/OrderList.vue'
import OrderStatistics from '@/views/OrderManagement/OrderStatistics.vue'

import CostReport from '@/views/ReportStatistics/CostReport.vue'
import DishStatistics from '@/views/ReportStatistics/DishStatistics.vue'
import ProfitAnalysis from '@/views/ReportStatistics/ProfitAnalysis.vue'
import SalesReport from '@/views/ReportStatistics/SalesReport.vue'

import EmployeeList from '@/views/user/EmployeeList.vue'
import LoginPage from '@/views/login/LoginPage.vue'

// 白名单列表
const whiteList = ['/login', '/404', '/401']

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginPage,
    meta: {
      requiresAuth: false,
      title: '登录'
    }
  },
  {
    path: '/',
    component: LayoutContainer,
    redirect: '/order/list',
    meta: {
      requiresAuth: true,
      title: '主页'
    },
    children: [
      {
        path: 'dish',
        name: 'DishManagement',
        meta: { title: '菜品管理' },
        redirect: '/dish/list',
        children: [
          {
            path: 'category',
            name: 'CategoryManagement',
            component: CategoryManagement,
            meta: { title: '分类管理' }
          },
          {
            path: 'cost',
            name: 'CostManagement',
            component: CostManagement,
            meta: { title: '成本管理' }
          },
          {
            path: 'list',
            name: 'DishList',
            component: DishList,
            meta: { title: '菜品列表' }
          },
          {
            path: 'flavor',
            name: 'FlavorManagement',
            component: FlavorManagement,
            meta: { title: '口味管理' }
          }
        ]
      },
      {
        path: 'perform',
        name: 'PerformCenter',
        meta: { title: '演出信息管理' },
        redirect: '/perform/performInfo',
        children: [
          {
            path: 'performInfo',
            name: 'PerformManagement',
            component: () => import('../views/PerformManagement/Perform/PerformCenter.vue'),
            meta: { title: '演出信息' },
          },
          {
            path: 'performer',
            name: 'PerformerManagement',
            component: () => import('../views/PerformManagement/Performer/PerformerInfo.vue'),
            meta: { title: '演出人员' },
          },
          {
            path: 'venue',
            name: 'VenueManagement',
            component: () => import('../views/PerformManagement/Venue/VenueInfo.vue'),
            meta: { title: '表演场地' },
          },
        ]
      },

      {
        path: 'order',
        name: 'OrderManagement',
        meta: { title: '订单管理' },
        redirect: '/order/list',
        children: [
          {
            path: 'history',
            name: 'HistoricalOrders',
            component: HistoricalOrders,
            meta: { title: '历史订单' }
          },
          {
            path: 'list',
            name: 'OrderList',
            component: OrderList,
            meta: { title: '订单列表' }
          },
          {
            path: 'statistics',
            name: 'OrderStatistics',
            component: OrderStatistics,
            meta: { title: '订单统计' }
          }
        ]
      },
      {
        path: 'report',
        name: 'ReportStatistics',
        meta: { title: '报表统计' },
        redirect: '/report/sales',
        children: [
          {
            path: 'cost',
            name: 'CostReport',
            component: CostReport,
            meta: { title: '成本报表' }
          },
          {
            path: 'dish-statistics',
            name: 'DishStatistics',
            component: DishStatistics,
            meta: { title: '菜品统计' }
          },
          {
            path: 'profit-analysis',
            name: 'ProfitAnalysis',
            component: ProfitAnalysis,
            meta: { title: '利润分析' }
          },
          {
            path: 'sales',
            name: 'SalesReport',
            component: SalesReport,
            meta: { title: '销售报表' }
          }
        ]
      },
      {
        path: 'user',
        name: 'UserManagement',
        meta: { title: '用户管理' },
        redirect: '/user/employee',
        children: [
          {
            path: 'employee',
            name: 'EmployeeList',
            component: EmployeeList,
            meta: { title: '员工列表' }
          }
        ]
      }
    ]
  },
  // 404路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 安全地获取用户token
const getToken = () => {
  try {
    const userJson = localStorage.getItem('big-user')
    if (!userJson) return null

    const userData = JSON.parse(userJson)
    return userData?.token || null
  } catch (err) {
    console.error('Token parsing failed:', err)
    return null
  }
}

// 更新页面标题
const setDocumentTitle = (title) => {
  document.title = title ? `${title} - 餐厅管理系统` : '餐厅管理系统'
}

// 路由守卫ss
router.beforeEach((to) => {
  // 更新页面标题
  setDocumentTitle(to.meta.title)

  // 如果是白名单页面，直接放行
  if (whiteList.includes(to.path)) {
    return true
  }

  // 获取token
  const token = getToken()

  // 如果没有token且不在白名单中，跳转到登录页
  if (!token) {
    return {
      path: '/login',
      query: {
        redirect: to.fullPath // 保存原本要去的路径
      }
    }
  }

  // 有token，放行
  return true
})

// 路由错误处理
router.onError((error) => {
  console.error('Router error:', error)
})

export default router
